<!--
  功能：初始化功能描述
  作者：zichen-jiang
  邮箱：18307106535@163.com
  版本：v1.0.2
  修改内容：vue2.0初始化模板
  修改人员：zicheng-jiang
  修订时间：2020.10.01
  组件生成时间：2022年06月18日 19:16:54
-->
<template>
  <div class="homePage">
    <Swiper class="animate__animated animate__shakeY" />
    <div class="animate__animated animate__bounceIn imgtab">
      <div :style="`width:${imgtabList.length * 85}px`">
        <span
          v-for="(item, index) in imgtabList"
          :key="index"
          :class="activedTab == index ? 'activedTab' : ''"
          @click="tabimg(item.id, index)"
        >{{ item.name }}</span>
      </div>
    </div>

    <!-- 图片区域 -->
    <ImeList ref="ImeList" />

    <!-- 添加图片 -->
    <div class="addimg animate__heartBeat" ref="addimg" @click="onAddImg" title="上传图片">
      <img src="@/assets/tj.png" alt />
    </div>

    <a-modal
      title="上传图片"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="取消"
      okText="确认"
    >
      <a-form :label-col="{ span: 3 }" :wrapper-col="{ span: 17 }">
        <a-form-item label="分类">
          <a-select style="width: 100%" v-model="imgclass" @change="handleChange">
            <a-select-option
              :value="item.id"
              v-for="(item, index) in imgtabList"
              :key="index"
            >{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea
            placeholder="请添加图片描述，有利于搜索"
            v-model="title"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          ></a-textarea>
        </a-form-item>
        <a-form-item label="图片">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :multiple="true"
            :show-upload-list="false"
            :customRequest="uploadImg"
            :accept="fileAccept"
            :beforeUpload="beforeUpload"
          >
            <img v-if="imageUrl" :src="baseUrl + imageUrl" alt="avatar" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
//import(导入)其他文件（如：组件，工具js，第三方插件js，json文件，图片文件等）
import { requset } from "@/api";
import Swiper from "./modules/swiper";
import ImeList from "./modules/imglist";
import { uploads } from "@/utils/upload";
import EventBus from "@/utils/EventBus";
export default {
  name: "homePage",
  /**注册组件*/
  components: { Swiper, ImeList },
  /**接受父组件传值*/
  props: {},
  data() {
    return {
      imgtabList: [],
      activedTab: 0,
      userInfo: JSON.parse(localStorage.getItem("userInfo")),
      visible: false,
      imgclass: "",
      title: "",
      loading: false,
      baseUrl: process.env.VUE_APP_API_BASE_URL,
      imageUrl: "",
      fileAccept: "image/gif, image/jpeg, image/jpg, image/png, image/svg",
      searchValue: ""
    };
  },
  /**计算属性*/
  computed: {},
  /**监听data数据变化*/

  watch: {},
  /**创建组件时执行(有VM对象this)*/
  created() {},
  /**加载完组件时执行(主要预处理数据)*/

  mounted() {
    EventBus.$on("onSearch", searchValue => {
      this.searchValue = searchValue;
    });
    // this.$nextTick(() => {
    //   const body = document.querySelector(".home");
    //   if (body.append) {
    //     body.append(this.$refs.addimg);
    //   } else {
    //     body.appendChild(this.$refs.addimg);
    //   }
    // });
    this.getimgtab();
  },
  /**所有方法*/
  methods: {
    // 查询tab列表
    getimgtab() {
      requset("get", "/imageTab/list", {}).then(res => {
        if (res.data.code == 200) {
          this.imgtabList = res.data.data;
          this.imgtabList.unshift({ id: "", name: "全部" });
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // tab切换
    tabimg(id, index) {
      this.activedTab = index;
      this.$refs.ImeList.id = id;
      this.reset();
    },
    onAddImg() {
      if (!localStorage.getItem("token") && !this.userInfo) {
        this.$notification.warning({
          message: "X站提示",
          description: "为响应国家治乱净网的号召，请先登录在进行上传！",
          placement: "bottomRight"
        });
      } else {
        this.visible = true;
      }
    },
    // 取消上传图片弹窗
    handleCancel(e) {
      // 如果图片已上传但未提交
      if (this.imageUrl != "") {
        let that = this;
        this.$confirm({
          title: "提示",
          content: "图片暂未提交，确定取消上传？",
          cancelText: "取消上传",
          okText: "继续上传",
          onOk() {},
          onCancel() {
            let params = {
              imageUrl: that.imageUrl
            };
            that.visible = false;
            requset("post", "/homeImg/deleteImg", params).then(res => {
              if ((res.data.code = 200)) {
                that.imageUrl = "";
              }
            });
          }
        });
      } else {
        this.visible = false;
      }
    },
    // 分类选择
    handleChange(value) {
      this.imgclass = value;
    },
    //上传文件前校验
    beforeUpload(file) {
      const extension1 = file.name.split(".")[1] === "jpg";
      const extension2 = file.name.split(".")[1] === "jpeg";
      const extension3 = file.name.split(".")[1] === "png";
      const extension4 = file.name.split(".")[1] === "gif";
      const extension5 = file.name.split(".")[1] === "svg";
      if (
        !extension1 &&
        !extension2 &&
        !extension3 &&
        !extension4 &&
        !extension5
      ) {
        this.$message.error("图片！图片！你懂什么叫图片么你就瞎往上传？");
      }
      return extension1 || extension2 || extension3 || extension4 || extension5;
    },
    //上传文件
    uploadImg(upload) {
      if (upload.file.size > 3000000) {
        this.$message.error("上传图片大小不得大于3MB");
        return;
      }
      this.loading = true;
      uploads("/homeImg/uploads", upload.file).then(res => {
        this.loading = false;
        if (res.data.code == 200) {
          this.imageUrl = res.data.imgUrl;
        }
      });
    },
    reset() {
      this.$refs.ImeList.pageIndex = 1;
      this.$refs.ImeList.listNull = false;
      this.$refs.ImeList.imglist = [];
      if (this.searchValue == "") {
        this.$refs.ImeList.getlist();
      } else {
        this.$refs.ImeList.Search(this.searchValue);
      }
    },
    handleOk() {
      if (this.imageUrl == "") {
        this.$message.error("请先上传图片");
        return;
      }
      let params = {
        classId: this.imgclass,
        title: this.title,
        url: this.imageUrl,
        creatUserPhone: this.userInfo.phone,
        creatUserName: this.userInfo.userName,
        creatuserImg: this.userInfo.userImg
      };
      requset("post", "/homeImg/create", params).then(res => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
          this.visible = false;
          this.reset();

          this.title = "";
          this.imgclass = "";
          this.imageUrl = "";
        } else if (res.data.code == 204) {
          this.visible = false;
          this.reset();

          this.title = "";
          this.imgclass = "";
          this.imageUrl = "";
          this.$message.warning(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
      });
    }
  }
};
</script>
<style scoped>
/* @import url(); 引入css类 */
.imgtab {
  width: 100%;
  /* height: 50px; */
  position: sticky;
  top: 52px;
  background: #fff;
  z-index: 99;
}
.imgtab span {
  display: inline-block;
  width: 70px;
  margin-right: 15px;
  height: 100%;
  text-align: center;
  line-height: 50px;
  cursor: pointer;
  font-weight: 600;
}
.imgtab span:hover {
  color: #1890ff;
}
.activedTab {
  border-bottom: 2px solid #1890ff;
  color: #1890ff;
}
.addimg {
  width: 50px;
  height: 50px;
  position: fixed;
  bottom: 50px;
  right: 30px;
}
.addimg:hover {
  cursor: pointer;
}
.addimg img {
  width: 100%;
  height: 100%;
}

/* 如果浏览器窗口小于 500px */
@media only screen and (max-width: 500px) {
  .imgtab {
    overflow-x: scroll;
  }
}
.avatar-uploader img {
  width: 100px;
  height: 100px;
}
</style>
